/**
 * 微信公众平台开发模式(JAVA) SDK
 * (c) 2012-2013 ____′↘夏悸 <wmails@126.cn>, MIT Licensed
 * http://www.jeasyuicn.com/wechat
 */
package com.gson;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.lang3.StringUtils;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.gson.bean.Articles;
import com.gson.bean.InMessage;
import com.gson.bean.MusicOutMessage;
import com.gson.bean.NewsOutMessage;
import com.gson.bean.OutMessage;
import com.gson.bean.TextOutMessage;
import com.gson.inf.MessageProcessingHandler;
import com.gson.inter.BaiduMusicService;
import com.gson.inter.BaiduPlaceService;
import com.gson.inter.BaiduWeatherService;
import com.gson.inter.LocateUtil;
import com.gson.inter.RssChild;
import com.gson.inter.RssViewer;
import com.gson.inter.So114Service;
import com.gson.inter.TodayInHistoryService;
import com.gson.model.Music;
import com.gson.model.PosInfoModel;
import com.gson.model.Weather;
import com.gson.model.WeatherData;
import com.gson.util.JodaTime;
import com.gson.util.PosInfoHandler;
import com.gson.util.Tools;

/**
 * 自定义实现消息处理
 * @author GodSon
 *
 */
public class MessageProcessingHandlerImpl implements MessageProcessingHandler {

	@Override
	public OutMessage textTypeMsg(InMessage msg) {
		TextOutMessage oms = new TextOutMessage();
		StringBuffer replyMsg = new StringBuffer();
		String content = msg.getContent().trim();
		if("?".equals(content)||"？".equals(content)){
			replyMsg.append("欢迎使用微信平台！");
			replyMsg.append("\r\n1、发送：天气+城市");
			replyMsg.append("\r\n\t\t\t 例如'天气上海'");
			replyMsg.append("\r\n\t\t\t 或者'上海天气'");
			replyMsg.append("\r\n2、发送：歌曲+歌名");
			replyMsg.append("\r\n\t\t\t 例如：歌曲存在");
			replyMsg.append("\r\n\t\t\t 或者：歌曲存在@汪峰");
			replyMsg.append("\r\n3、焦点新闻");
			replyMsg.append("\r\n4、历史上的今天");
			replyMsg.append("\r\n5、发送：地区空格关键词");
			replyMsg.append("\r\n\t\t\t 例如'上海 银行'");
			replyMsg.append("\r\n其他、回音壁请直接输入文字信息");
			oms.setContent(replyMsg.toString());
		}else if("3".equals(content)){
			NewsOutMessage nom = new NewsOutMessage();
			List<Articles> articleList = new ArrayList<Articles>();
			String rss_url = "http://news.google.com/news?pz=1&cf=all&ned=cn&hl=zh-CN&output=rss";
			try {
				RssViewer new_viewer = new RssViewer(rss_url);
				ArrayList item_list = new_viewer.getRSS_items();
				Iterator itx = item_list.iterator();

				while (itx.hasNext()) {
					Articles articles = new Articles();
					RssChild rsschild = (RssChild) itx.next();
					articles.setTitle(rsschild.getTitle());
					String link = rsschild.getLink();
					link = link.substring(link.indexOf("&url=")+5);
					articles.setUrl(link);
					
					articleList.add(articles);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			nom.setArticles(articleList);
			nom.setFuncFlag(0);
			return nom;
		}else if("4".equals(content)){
			String info = TodayInHistoryService.getTodayInHistoryInfo();
			oms.setContent(info);
		}else if(Tools.checkCNet(content)){
			LocateUtil util = new LocateUtil();
			try {
				String rtnXml = util.getMobileLocateInfo(content);
				if(StringUtils.isEmpty(rtnXml)){
					oms.setContent("\ue401定位结果为空");
				}
				
				//解析返回结果
				PosInfoModel posInfo = null;
				SAXParserFactory factory = SAXParserFactory.newInstance();
				SAXParser parser = factory.newSAXParser();
				XMLReader xmlReader = parser.getXMLReader();
				PosInfoHandler handler = new PosInfoHandler();
				xmlReader.setContentHandler(handler);
				StringReader sr = new StringReader(rtnXml);
				InputSource is = new InputSource(sr);
				xmlReader.parse(is);
				posInfo = handler.getPosInfo();
				
				if(posInfo==null) {
					oms.setContent("\ue401暂时无法定位，请稍后再试！");
				} else if(posInfo.isErrorFlag()==true){
					oms.setContent("\ue401暂时无法定位，请稍后再试");
				}else{
					NewsOutMessage nom = new NewsOutMessage();
					List<Articles> articleList = util.getGoogleMap(posInfo, content);
					
					nom.setArticles(articleList);
					nom.setFuncFlag(0);
					return nom;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		// 如果以“歌曲”2个字开头
		}else if (content.startsWith("歌曲")) {
			// 将歌曲2个字及歌曲后面的+、空格、-等特殊符号去掉  
            String keyWord = content.replaceAll("^歌曲[\\+ ~!@#%^-_=]?", "");
            // 如果歌曲名称为空  
            if ("".equals(keyWord)) {  
            	oms.setContent(getUsage());
            } else {  
                String[] kwArr = keyWord.split("@");  
                // 歌曲名称  
                String musicTitle = kwArr[0];  
                // 演唱者默认为空  
                String musicAuthor = "";  
                if (2 == kwArr.length)  
                    musicAuthor = kwArr[1];  

                // 搜索音乐  
                Music music = BaiduMusicService.searchMusic(musicTitle, musicAuthor);  
                // 未搜索到音乐  
                if (null == music) {  
                    oms.setContent("对不起，没有找到你想听的歌曲<" + musicTitle + ">。");
                } else {  
                    // 音乐消息  
                	MusicOutMessage mom = new MusicOutMessage();
        			
        			mom.setMusic(music);
        			mom.setFuncFlag(0);
        			return mom;
                }  
            } 
         // 如果以“天气”2个字开头
        }else if (content.startsWith("天气") || content.endsWith("天气")) {
        	// 将天气2个字及天气后面的+、空格、-等特殊符号去掉  
            String keyWord = content.replaceAll("^天气[\\+ ~!@#%^_=]?", "").trim();
            if(keyWord.indexOf("天气")>=0){
            	keyWord = content.replaceAll("[-\\+ ~!@#%^_=]?天气$", "").trim();
            }
            // 如果城市名称为空  
            if ("".equals(keyWord)) {  
            	oms.setContent(getWeatherUsage());
            } else {
            	// 搜索天气  
            	Weather weather = BaiduWeatherService.searchWeather(keyWord);
            	if("success".equals(weather.getStatus())) {
            		List<WeatherData> weatherDataList = weather.getResults();
            		if(weatherDataList!=null && weatherDataList.size()>0) {
            			NewsOutMessage nom = new NewsOutMessage();
            			List<Articles> articleList = new ArrayList<Articles>();
    					
    					Articles articles = null;
    					StringBuilder sb = null;
    					for (int i = 0; i < weatherDataList.size(); i++) {
    						articles = new Articles();
    						
    						sb = new StringBuilder();
            				sb.append(weatherDataList.get(i).getDate());
            				sb.append(weatherDataList.get(i).getTemperature());
            				sb.append(weatherDataList.get(i).getWeather());
            				sb.append(weatherDataList.get(i).getWind());
            				articles.setTitle(sb.toString());
            				
            				if(i==0) {
            					int hour = JodaTime.getHour();
                				if(hour>5 && hour<18) {
                					articles.setPicUrl(weatherDataList.get(i).getDayPictureUrl());
                				} else {
                					articles.setPicUrl(weatherDataList.get(i).getNightPictureUrl());
                				}
            				} else {
            					articles.setPicUrl(weatherDataList.get(i).getDayPictureUrl());
            				}
            				
            				articleList.add(articles);
						}
            			
            			nom.setArticles(articleList);
    					nom.setFuncFlag(0);
            			return nom;
            		} else {
            			oms.setContent(getWeatherUsage());
            		}
            	} else {
            		oms.setContent(getWeatherUsage());
            	}
            	
            }
		} else if (content.indexOf(" ") >= 0) {
			String[] word = content.split(" ");
			
			So114Service so114Service = new So114Service();
			String result = so114Service.doSearch(content);
			
			if(StringUtils.isNotEmpty(result)) {
				oms.setContent(result);
			} else {
				oms.setContent(getOrgSearchUsage());
			}

		} else {
			oms.setContent(content);
		}
		return oms;
	}

	@Override
	public OutMessage locationTypeMsg(InMessage msg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public OutMessage imageTypeMsg(InMessage msg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public OutMessage linkTypeMsg(InMessage msg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public OutMessage eventTypeMsg(InMessage msg) {
		StringBuffer replyMsg = new StringBuffer();
		if("subscribe".equals(msg.getEvent())){
			TextOutMessage oms = new TextOutMessage();
			replyMsg.append("欢迎使用微信平台！");
			replyMsg.append("\r\n1、发送：天气+城市");
			replyMsg.append("\r\n\t\t\t 例如'天气上海'");
			replyMsg.append("\r\n\t\t\t 或者'上海天气'");
			replyMsg.append("\r\n2、发送：歌曲+歌名");
			replyMsg.append("\r\n\t\t\t 例如：歌曲存在");
			replyMsg.append("\r\n\t\t\t 或者：歌曲存在@汪峰");
			replyMsg.append("\r\n3、焦点新闻");
			replyMsg.append("\r\n4、历史上的今天");
			replyMsg.append("\r\n5、发送：地区空格关键词");
			replyMsg.append("\r\n\t\t\t 例如'上海 银行'");
			replyMsg.append("\r\n其他、回音壁请直接输入文字信息");
			oms.setContent(replyMsg.toString());
			return oms;
		}
		return null;
	}

	@Override
	public OutMessage voiceTypeMsg(InMessage msg) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/** 
     * 歌曲点播使用指南 
     *  
     * @return 
     */  
    public static String getUsage() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("歌曲点播操作指南").append("\n\n");  
        buffer.append("回复：歌曲+歌名").append("\n");  
        buffer.append("例如：歌曲存在").append("\n");  
        buffer.append("或者：歌曲存在@汪峰").append("\n\n");  
        buffer.append("回复“?”显示主菜单");  
        return buffer.toString();  
    } 
    
	/** 
     * 歌曲查询使用指南 
     *  
     * @return 
     */  
    public static String getWeatherUsage() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("天气查询操作指南").append("\n\n");  
        buffer.append("回复：天气+城市").append("\n");  
        buffer.append("例如：天气北京").append("\n");  
        buffer.append("或者：北京天气").append("\n");  
        buffer.append("回复“?”显示主菜单");  
        return buffer.toString();  
    } 
    
	/** 
     * 歌曲查询使用指南 
     *  
     * @return 
     */  
    public static String getOrgSearchUsage() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("商家查询操作指南").append("\n\n");  
        buffer.append("发送：地区空格关键词").append("\n");  
        buffer.append("例如：上海 银行").append("\n");  
        buffer.append("回复“?”显示主菜单");  
        return buffer.toString();  
    } 

}
